package filter;

import util.TokenUtil;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class LoginFiter extends HttpFilter {
    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        // 解决跨域问题
        ((HttpServletResponse) resp).setHeader("Access-Control-Allow-Methods", "POST, GET, DELETE");
        HttpServletRequest request=(HttpServletRequest) req;
        HttpServletResponse response=(HttpServletResponse) resp;
        //获取请求资源路径
        String requestURI = request.getRequestURI();
        //3.判断是否包含登录相关资源路径
        //需要加个判断 判断该请求是否为OPTIONS请求
        if ( requestURI.contains("LoginServlet")||"OPTIONS".equals(request.getMethod())) {
            // 这是登录界面，放行
            chain.doFilter(req, resp);
        } else {
            //4.判断是否有token
            String token= request.getHeader("Token");
            if(token!=null){
                boolean verify = TokenUtil.verify(token);
                if(verify){
                    chain.doFilter(req, resp);
                }else {
                    response.setStatus(401);
                    System.out.println("token无效，401");
                }
            }else {
                System.out.println(request.getMethod());
                System.out.println("token不存在，401");
                response.setStatus(401);
            }
        }
    }
}
